package initialize

import (
	"bookProject/global"
	"bookProject/proto"
	"bookProject/routers"
	"bookProject/vender/consul"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/hashicorp/consul/api"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"gopkg.in/yaml.v2"
)

func init() {
	InitConfig()       //配置文件
	InitalizeLoggeer() //日志包
	InitalizeRouter()  // 路由
	InitConsul()       //consul
	InitUserRpc()      //grpc连接
}

func InitConfig() {
	//默认加载配置项  以全局变量的形式输出go
	//初始化
	v := viper.New()
	//设置配置文件
	v.SetConfigFile("./application-dev.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	NacosConfig := global.NacosConfig{}
	//读取的时候层级关系对应
	if err := v.Unmarshal(&NacosConfig); err != nil {
		panic(err)
	}
	global.NacosServer = &NacosConfig
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "", // 如果需要支持多namespace，我们可以创建多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	// 至少一个ServerConfig
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: global.NacosServer.Host,
			Port:   global.NacosServer.Port,
		},
	}

	// 创建动态配置客户端
	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	//获取配置：GetConfig
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: global.NacosServer.DataId,
		Group:  global.NacosServer.Group})
	if err != nil {
		panic(err)
	}
	//json转译  映射到结构体
	ServerConfig := global.ServerConfig{}
	//想要将一个json字符串转换成struct，需要去设置这个struct的tag
	yaml.Unmarshal([]byte(content), &ServerConfig)
	global.GlobalConfig = &ServerConfig
}

func InitalizeLoggeer() {
	config := zap.NewDevelopmentConfig()
	config.OutputPaths = []string{
		global.GlobalConfig.Service.LogPath,
		"stderr",
		"stdout",
	}
	//构建并初始化
	logger, _ := config.Build()
	//替换为全局变量
	zap.ReplaceGlobals(logger)
}

func InitalizeRouter() {
	//建立Api的路由
	router := gin.Default()
	router.Use(corsMiddleware())
	//路由组  -- 版本组  --业务组    版本组包含业务组
	apiRouter := router.Group("/v1") // http://127.0.0.1:8080/v1/user/register
	routers.UserRouter(apiRouter)
	global.Router = router
}

func corsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "http://localhost:9528")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization")
		c.Header("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(200)
		} else {
			c.Next()
		}
	}
}

func InitConsul() {
	//初始化配置
	config := api.DefaultConfig()
	//通过配置进行实例化
	client, err := api.NewClient(config)
	if err != nil {
		panic(err)
	}
	global.ConsuleClient = client
	//实例化consul调用类
	consulClient := consul.NewRegistryClient(global.GlobalConfig.Consule.Host, global.GlobalConfig.Consule.Port)
	serviceId := uuid.NewV4().String()
	//调用服务过滤接口 -- 判断哪个过滤哪个
	filterResult := consulClient.FilterService(global.GlobalConfig.Consule.Name)
	BaseSrvIp := ""
	for _, value := range filterResult {
		BaseSrvIp = value.Address
		break
	}
	if BaseSrvIp == "" {
		err = consulClient.RegisterConsul(global.GlobalConfig.Consule.Name, global.GlobalConfig.Consule.Port, global.GlobalConfig.Consule.Name, global.GlobalConfig.Consule.Tag, serviceId)
		if err != nil {
			panic(err)
			zap.S().Panic("服务注册失败:", err.Error())
		}
	} else {
		zap.S().Info("服务已经注册，无需再次注册")
	}
}

// // 连接rpc端
func InitUserRpc() {
	//使用consule的过滤方法 从consule中直接拿到rpc端的服务信息
	result, err := global.ConsuleClient.Agent().ServicesWithFilter(fmt.Sprintf(`Service == "%s"`, global.GlobalConfig.UserSrv.Name))

	//将grpc封装成全局调用（之前是单个接口调用）
	userSrvIp := ""
	userPort := 0
	for _, value := range result {
		userSrvIp = value.Address
		userPort = value.Port
		break
	}
	//如果没有取到rpc端服务的host地址 那么直接输出错误
	if userSrvIp == "" {
		zap.S().Info("连接rpc端失败", err)
		panic(err)
	}
	userClient, err := grpc.Dial(
		fmt.Sprintf("%s:%d", userSrvIp, userPort),
		grpc.WithTransportCredentials(insecure.NewCredentials()),
		//grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy"："round_robin"}`), //负载的方式
	)
	userSrvClient := proto.NewUserClient(userClient)
	global.UserClient = userSrvClient
}
